#include "pwext.hpp"
#include <stdio.h>
#include <unistd.h>


// DEBUG {

pw::autoevent ae;

class waiter : public pw::pwthread
{
public:
	// auto-start on construction and stop before destruction
	waiter()
	{
		start();
	}
	~waiter()
	{
		join();
	}
	void *execute()
	{
		ae.wait();
		fprintf(stderr, "wait succeeded\n");
		return 0;
	}
};

int main()
{
	ae.pulse();
	if (ae.trywait() == ETIMEDOUT)
		fprintf(stderr, "trywait failed as expected\n");

	{
		waiter w1;
		ae.signal();
	}
	{
		waiter w1;
		usleep(100*1000);
		ae.pulse();
	}

	ae.signal();
	ae.signal();
	if (ae.trywait() == 0)
		fprintf(stderr, "trywait succeeded as expected\n");
	if (ae.trywait() == ETIMEDOUT)
		fprintf(stderr, "trywait failed as expected\n");

	struct timespec endtime;
	clock_gettime(CLOCK_REALTIME, &endtime); // the current time
	if (ae.timedwait(endtime) == ETIMEDOUT)
		fprintf(stderr, "timedwait failed as expected\n");
	ae.signal();
	if (ae.timedwait(endtime) == 0)
		fprintf(stderr, "timedwait succeeded as expected\n");
	return 0;
}
// DEBUG }
/* Sample output:

trywait failed as expected
wait succeeded
wait succeeded
trywait succeeded as expected
trywait failed as expected
timedwait failed as expected
timedwait succeeded as expected

*/
